{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 文本预处理",
   "id": "aaef319f9bec44fb"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 1. 读取数据集\n",
    "\n",
    "首先，我们从H.G.Well的[时光机器](https://www.gutenberg.org/ebooks/35)中加载文本。 这是一个相当小的语料库，只有30000多个单词。下面的函数将数据集读取到由多条文本行组成的列表中，其中每条文本行都是一个字符串。 为简单起见，我们在这里忽略了标点符号和字母大写。"
   ],
   "id": "bef02c85319026ce"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T05:31:49.903475Z",
     "start_time": "2024-08-28T05:31:49.891952Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import re\n",
    "\n",
    "\n",
    "def read_time_machine():  # @save\n",
    "    \"\"\"将时间机器数据集加载到文本行的列表中\"\"\"\n",
    "    with open('time_machine.txt', 'r') as f:\n",
    "        lines = f.readlines()\n",
    "    return [re.sub('[^A-Za-z]+', ' ', line).strip().lower() for line in lines]\n",
    "\n",
    "\n",
    "lines = read_time_machine()\n",
    "print(f'# 文本总行数: {len(lines)}')\n",
    "print(lines[0])\n",
    "print(lines[10])"
   ],
   "id": "a72880ba0e9b5234",
   "execution_count": 1,
   "outputs": []
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 2. 词元化\n",
    "\n",
    "下面的tokenize函数将文本行列表（lines）作为输入， 列表中的每个元素是一个文本序列（如一条文本行）。 每个文本序列又被拆分成一个词元列表，词元（token）是文本的基本单位。 最后，返回一个由词元列表组成的列表，其中的每个词元都是一个字符串（string）。"
   ],
   "id": "facb7d7de78c3095"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T05:31:49.909530Z",
     "start_time": "2024-08-28T05:31:49.905101Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def tokenize(lines, token='word'):  #@save\n",
    "    \"\"\"将文本行拆分为单词或字符词元\"\"\"\n",
    "    if token == 'word':\n",
    "        return [line.split() for line in lines]\n",
    "    elif token == 'char':\n",
    "        return [list(line) for line in lines]\n",
    "    else:\n",
    "        print('错误：未知词元类型：' + token)\n",
    "\n",
    "\n",
    "tokens = tokenize(lines)\n",
    "for i in range(11):\n",
    "    print(tokens[i])"
   ],
   "id": "a05fbe689b2a2cd6",
   "execution_count": 2,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T05:31:49.914886Z",
     "start_time": "2024-08-28T05:31:49.910332Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import collections\n",
    "\n",
    "\n",
    "class Vocab:  #@save\n",
    "    \"\"\"文本词表\"\"\"\n",
    "\n",
    "    def __init__(self, tokens=None, min_freq=0, reserved_tokens=None):\n",
    "        '''\n",
    "        :param tokens: 传入词元\n",
    "        :param min_freq: 最小词频，出现过少则不要 \n",
    "        :param reserved_tokens: \n",
    "        '''\n",
    "        if tokens is None:\n",
    "            tokens = []\n",
    "        if reserved_tokens is None:\n",
    "            reserved_tokens = []\n",
    "        # 按出现频率排序\n",
    "        counter = count_corpus(tokens)\n",
    "        self._token_freqs = sorted(counter.items(), key=lambda x: x[1], reverse=True)\n",
    "        # 未知词元的索引为0\n",
    "        self.idx_to_token = ['<unk>'] + reserved_tokens\n",
    "        self.token_to_idx = {token: idx for idx, token in enumerate(self.idx_to_token)}\n",
    "        for token, freq in self._token_freqs:\n",
    "            if freq < min_freq:\n",
    "                break\n",
    "            if token not in self.token_to_idx:\n",
    "                self.idx_to_token.append(token)\n",
    "                self.token_to_idx[token] = len(self.idx_to_token) - 1\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.idx_to_token)\n",
    "\n",
    "    def __getitem__(self, tokens):\n",
    "        if not isinstance(tokens, (list, tuple)):\n",
    "            return self.token_to_idx.get(tokens, self.unk)\n",
    "        return [self.__getitem__(token) for token in tokens]\n",
    "\n",
    "    def to_tokens(self, indices):\n",
    "        if not isinstance(indices, (list, tuple)):\n",
    "            return self.idx_to_token[indices]\n",
    "        return [self.idx_to_token[index] for index in indices]\n",
    "\n",
    "    @property\n",
    "    def unk(self):  # 未知词元的索引为0\n",
    "        return 0\n",
    "\n",
    "    @property\n",
    "    def token_freqs(self):\n",
    "        return self._token_freqs\n",
    "\n",
    "\n",
    "def count_corpus(tokens):  #@save\n",
    "    \"\"\"统计词元的频率\"\"\"\n",
    "    # 这里的tokens是1D列表或2D列表\n",
    "    if len(tokens) == 0 or isinstance(tokens[0], list):\n",
    "        # 将词元列表展平成一个列表\n",
    "        tokens = [token for line in tokens for token in line]\n",
    "    return collections.Counter(tokens)"
   ],
   "id": "963acbdf35f41087",
   "execution_count": 3,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T05:31:49.922876Z",
     "start_time": "2024-08-28T05:31:49.916270Z"
    }
   },
   "cell_type": "code",
   "source": [
    "vocab = Vocab(tokens)\n",
    "print(list(vocab.token_to_idx.items())[:10])"
   ],
   "id": "9a261c35ec33d2ae",
   "execution_count": 4,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T05:31:49.927092Z",
     "start_time": "2024-08-28T05:31:49.924079Z"
    }
   },
   "cell_type": "code",
   "source": [
    "for i in [0, 10]:\n",
    "    # 有几个是[]\n",
    "    print('文本:', tokens[i])\n",
    "    print('索引:', vocab[tokens[i]])"
   ],
   "id": "c9e000d8edf633f",
   "execution_count": 5,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T05:31:49.972532Z",
     "start_time": "2024-08-28T05:31:49.928071Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def load_corpus_time_machine(max_tokens=-1):  #@save\n",
    "    \"\"\"返回时光机器数据集的词元索引列表和词表\"\"\"\n",
    "    lines = read_time_machine()\n",
    "    tokens = tokenize(lines, 'char')\n",
    "    vocab = Vocab(tokens)\n",
    "    # 因为时光机器数据集中的每个文本行不一定是一个句子或一个段落，\n",
    "    # 所以将所有文本行展平到一个列表中\n",
    "    corpus = [vocab[token] for line in tokens for token in line]\n",
    "    if max_tokens > 0:\n",
    "        corpus = corpus[:max_tokens]\n",
    "    return corpus, vocab\n",
    "\n",
    "\n",
    "corpus, vocab = load_corpus_time_machine()\n",
    "len(corpus), len(vocab)"
   ],
   "id": "45fffbda7513e46d",
   "execution_count": 6,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T05:31:49.974684Z",
     "start_time": "2024-08-28T05:31:49.973168Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "7916bed81dd8d714",
   "execution_count": 6,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
